package com.yuan.pdftest.test.pdf.hg;


import com.lowagie.text.pdf.BaseFont;
import freemarker.template.Configuration;
import freemarker.template.Template;
import org.xhtmlrenderer.pdf.ITextFontResolver;
import org.xhtmlrenderer.pdf.ITextRenderer;

import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.StringWriter;
import java.net.URLEncoder;
import java.util.Locale;
import java.util.Map;

public class PdfPrintUntils {

    public static void exportPdfByFreeMarkerss(String mouldName, Map<String,Object> dataMap, String fileName, HttpServletResponse response) throws Exception {
        Configuration configuration = new Configuration(Configuration.DEFAULT_INCOMPATIBLE_IMPROVEMENTS);
        configuration.setClassForTemplateLoading(PdfPrintUntils.class, "/templates");
        ITextRenderer renderer = new ITextRenderer();
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        StringWriter writer = new StringWriter();
        try {
            // 设置 css中 的字体样式（暂时仅支持宋体和黑体） 必须，不然中文不显示
            ITextFontResolver fontResolver = renderer.getFontResolver();
            fontResolver.addFont("/templates/font/SIMSUN.TTC", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
            // 设置模板的编码格式
            configuration.setEncoding(Locale.CHINA, "UTF-8");
            // 获取模板文件
            mouldName="pdf测试模板.ftl";
            System.out.println(mouldName);
            Template template = configuration.getTemplate(mouldName, "UTF-8");
            // 将数据输出到html中
            template.process(dataMap, writer);
            writer.flush();
            String html = writer.toString();
            System.out.println(html);
            // 把html代码传入渲染器中
            renderer.setDocumentFromString(html);
            renderer.layout();
            renderer.createPDF(out, true);
            out.flush();
            renderer.finishPDF();
            response.setContentType("application/x-msdownload");
            String fileName2 = URLEncoder.encode(fileName+".pdf" , "UTF-8");
            response.setHeader( "Content-Disposition", "attachment;filename=" + fileName2);
            out.writeTo(response.getOutputStream());
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (writer != null) {
                writer.close();
            }
            if (out != null) {
                out.close();
            }
        }}
}